//
//  ViewController.m
//  原生定位和地理编码
//
//  Created by Hello Cai on 2021/7/6.
//

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController ()<CLLocationManagerDelegate>

@property(nonatomic, strong)CLLocationManager *locationManager;
@property(nonatomic, strong)CLGeocoder *geoCoder;   //地里编码


@property (weak, nonatomic) IBOutlet UILabel *addressLab;

@property (weak, nonatomic) IBOutlet UITextView *addressTV;
@property (weak, nonatomic) IBOutlet UITextField *latitudeTF;
@property (weak, nonatomic) IBOutlet UITextField *longitudeTF;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (IBAction)locationClick:(id)sender {
    //开始连续定位
    [self.locationManager startUpdatingLocation];
}


//地理编码（地址->经纬度）
- (IBAction)geoCodeClick:(id)sender {
    [self.geoCoder geocodeAddressString:self.addressTV.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error) {
            NSLog(@"地理编码error:%@", error);
        }else{
            CLPlacemark *pl = placemarks.firstObject;
            self.latitudeTF.text = [@(pl.location.coordinate.latitude) stringValue];
            self.longitudeTF.text = [@(pl.location.coordinate.longitude) stringValue];
        }
    }];
}

//逆地理编码（经纬度->地址）
- (IBAction)reverseGeoCodeClick:(id)sender {
    //反地理编码（经纬度->地址名称）
    CLLocationDegrees latitude = [self.latitudeTF.text doubleValue];
    CLLocationDegrees longitude = [self.longitudeTF.text doubleValue];
    CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
    [self.geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error) {
            NSLog(@"逆地理编码error:%@", error);
        }else{
            CLPlacemark *pl = placemarks.firstObject;
            self.addressTV.text = [NSString stringWithFormat:@"%@ %@ %@ %@", pl.administrativeArea,
                                   pl.locality,
                                   pl.subLocality,
                                   pl.thoroughfare];
        }
    }];
}



#pragma mark CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation *location = [locations lastObject];
    NSLog(@"location经纬度:%.3f,%.3f", location.coordinate.latitude, location.coordinate.longitude);
    
    //反地理编码（经纬度->地址名称）
    [self.geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if (error == nil) {
            /*
             打印结果：广东省,广州市,番禺区,大学城青蓝街28号创智大厦5栋506-508室
             administrativeArea：省
             locality：城市
             subLocality：小区
             thoroughfare：街道地址
             */
            CLPlacemark *pl = placemarks.firstObject;
            NSLog(@"%@,%@,%@,%@",
                  pl.administrativeArea,
                  pl.locality,
                  pl.subLocality,
                  pl.thoroughfare);
            self.addressLab.text = [NSString stringWithFormat:@"%@ %@ %@ %@", pl.administrativeArea,
                                    pl.locality,
                                    pl.subLocality,
                                    pl.thoroughfare];
        }else{
            NSLog(@"error:%@", error);
        }
    }];
    //结束连续定位
    [manager stopUpdatingLocation];
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    /*
     typedef NS_ENUM(int, CLAuthorizationStatus) {
         kCLAuthorizationStatusNotDetermined = 0,
         kCLAuthorizationStatusRestricted,
         kCLAuthorizationStatusDenied,
         kCLAuthorizationStatusAuthorizedAlways API_AVAILABLE(macos(10.12), ios(8.0)),
         kCLAuthorizationStatusAuthorizedWhenInUse API_AVAILABLE(ios(8.0)) API_UNAVAILABLE(macos),
     };
     */
    //iOS14系统在弹出授权定位弹窗，用户未选择任何选项的情况下会回调到该代理方法中，这是苹果的Bug，过滤掉
    //如果用户选择的是“不允许”，也会回调该方法，但authorizationStatus的值为kCLAuthorizationStatusDenied
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        return;
    }
    NSLog(@"error:%@", error);
}

-(CLLocationManager *)locationManager{
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        //请求前台、后台定位授权
        /*
          info.plist必须设置
          NSLocationAlwaysAndWhenInUseUsageDescription、NSLocationWhenInUseUsageDescription
         */
        [_locationManager requestAlwaysAuthorization];
        
        //请求前台定位授权
        /*
          info.plist必须设置NSLocationWhenInUseUsageDescription
          如果想要后台也能获得定位，Signing & Capabilities->Backgroud Modes要勾选Location updates，且iOS9以上必须设置allowsBackgroundLocationUpdates为YES
         */
//        [_locationManager requestWhenInUseAuthorization];
//        if (@available(iOS 9.0, *)) {
//            _locationManager.allowsBackgroundLocationUpdates = YES;
//        }
    }
    return _locationManager;
}

-(CLGeocoder *)geoCoder{
    if (!_geoCoder) {
        _geoCoder = [[CLGeocoder alloc] init];
    }
    return _geoCoder;
}
@end
